//
//  MyKeepViewController.m
//  NOAHWM
//
//  Created by Frank on 6/19/13.
//  Copyright (c) 2013 Ryan. All rights reserved.
//

#import "MyKeepViewController.h"
#import "NYMemberCenterDataManager.h"
#import "JSON.h"
#import "NYProduct.h"
#import "OnlineProductTableCell.h"
#import "ProductDetailViewController.h"
#import "MenuDataManager.h"
#import "NYProductDetail.h"

static NSInteger kNumOfPage = 10;
static NSInteger kInitPageNum = 1;
static NSInteger kCurrentPageNum = 1;

@interface MyKeepViewController ()

@end

@implementation MyKeepViewController

@synthesize keepProductTableView;
@synthesize keepProductList;
@synthesize moreView;
@synthesize placeHolderImageView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (MoreView *)moreView
{
    if(nil == moreView)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"MoreView" owner:self options:nil];
        moreView = [[nibs lastObject] retain];
        moreView.delegate = self;
    }
    return moreView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    [self setNaviTitle: @"收藏产品列表"];
    [self refreshProductsList];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(freshMyKeepList:) name:kmyKeepFreshNotification object:nil];

}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    if (self.isViewLoaded&&!self.view.window) {
        self.keepProductList = nil;
        self.keepProductTableView = nil;
        self.moreView = nil;
        self.placeHolderImageView = nil;
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    self.keepProductTableView = nil;
    self.keepProductList = nil;
    self.moreView = nil;
    self.placeHolderImageView = nil;
}

- (void)dealloc
{
    [placeHolderImageView release];
    [keepProductList release];
    [keepProductTableView release];
    [moreView release];
    [super dealloc];
}
#pragma mark - notification methord
- (void)freshMyKeepList: (NSNotification *)notification
{
    NSString* toCancelID = notification.object;
    
    for(NYProduct* item in self.keepProductList)
    {
        if ([item.collection_id isEqualToString:toCancelID]) {
            [self.keepProductList removeObject:item];
            break;
        }
    }
    [self.keepProductTableView reloadData];
}

#pragma mark - public methord
- (void)refreshProductsList
{
    kCurrentPageNum = kInitPageNum;
    [self callServerToGetMyKeep];
}

- (void)callServerToGetMyKeep
{
     NSString *accountId = [NYMemberCenterDataManager sharedManager].loginMember.accountId;
     [self callServerToGetMyKeepList:accountId  pageNo:[NSString stringWithFormat:@"%d",kCurrentPageNum] pageSize:[NSString stringWithFormat:@"%d",kNumOfPage] updateTime:@""];
}

- (void)callServerToGetMyKeepList:(NSString *)accountId
                                   pageNo:(NSString *)pageNo
                                 pageSize:(NSString *)pageSize
                               updateTime:(NSString *)updateTime
{
    NSString *suburl = [NSString stringWithFormat:kMykeepUrl,@"jsonp",accountId,pageNo,pageSize,updateTime];
    suburl = [suburl stringByAppendingString:@"app000049"];
    NSString *url = [NSString stringWithFormat:@"%@%@",kServerAddress,suburl];
    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    [[RYDownloaderManager sharedManager] requestDataByGetWithURLString:url delegate:self purpose:nil];
}

#pragma mark - RYDownloaderDelegate methods
- (void)downloader:(RYDownloader*)downloader completeWithNSData:(NSData*)data
{
    NSString *str = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
    str = [str stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    //去掉被包的jsonp字串
    if(str.length > 7)
        str = [str substringWithRange:NSMakeRange(6, str.length-7)];
    NSDictionary *dict = [str JSONValue];
    if([[dict objectForKey:@"result"] isEqualToString:@"1"])
    {
        self.keepProductTableView.hidden = NO;
        self.placeHolderImageView.hidden = YES;
        if(kCurrentPageNum == kInitPageNum)
            self.keepProductList = [NSMutableArray array];
        NSArray *array = [dict objectForKey:@"list"];
        for(NSDictionary *dict in array)
        {
            NYProduct *nyp = [[NYProduct alloc] init];
            for(NSString *key in [dict allKeys])
            {
                @try {
                    [nyp setValue:[dict objectForKey:key] forKey:key];
                }
                @catch (NSException *exception) {
                    NSLog(@"试图添加不存在的key: %@到NYProduct实例中.",key);
                }
            }
            [self.keepProductList addObject:nyp];
            [nyp release];
        }
        
        
        if(array.count == kNumOfPage)
            self.keepProductTableView.tableFooterView = self.moreView;
        else
            self.keepProductTableView.tableFooterView = nil;
        
        //重新加载产品列表
        [self.keepProductTableView reloadData];

    }
    else
    {
        [[RYHUDManager sharedManager] showWithMessage:[dict objectForKey:@"message"] customView:nil hideDelay:2.f];
        self.keepProductTableView.tableFooterView = nil;
    }
    if(self.keepProductList.count == 0)
    {
        self.keepProductTableView.hidden = YES;
        self.placeHolderImageView.hidden = NO;
        self.placeHolderImageView.image = [UIImage imageNamed:@"nodata.png"];
    }
    else
    {
        self.keepProductTableView.hidden = NO;
        self.placeHolderImageView.hidden = YES;
    }
}
- (void)downloader:(RYDownloader*)downloader didFinishWithError:(NSString*)message
{
    self.keepProductTableView.hidden = YES;
    self.placeHolderImageView.hidden = NO;
    self.placeHolderImageView.image = [UIImage imageNamed:@"nodata.png"];
    [[RYHUDManager sharedManager] showWithMessage:kNetWorkErrorString customView:nil hideDelay:2.f];
}

#pragma mark - UITableViewDataSource methods
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.keepProductList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentify = @"cellIdentify";
    OnlineProductTableCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentify];
    if(nil == cell)
    {
        NSArray *nibs = [[NSBundle mainBundle] loadNibNamed:@"OnlineProductTableCell" owner:self options:nil];
        cell = [nibs lastObject];
        UIImageView *bgView = [[UIImageView alloc] initWithFrame:cell.bounds];
        bgView.image = [UIImage imageNamed:@"bg_selection@2x.png"];
        cell.selectedBackgroundView = bgView;
        [bgView release];
    }
    NYProduct *nyp = [self.keepProductList objectAtIndex:indexPath.row];
    
    CGRect rect = cell.textContainView.frame;
    
    NSString *imagePath = nyp.img_url;
    if(imagePath)
        imagePath = [imagePath stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
    
    if(imagePath && ![imagePath isEqualToString:@""])
    {
        rect.size.width = 240.f;
        cell.iconImageView.hidden = NO;
        [cell.iconImageView aysnLoadImageWithUrl:imagePath placeHolder:@"loading_icon@2x.png"];
    }
    else
    {
        rect.size.width = tableView.frame.size.width-10.f;
        cell.iconImageView.hidden = YES;
    }
    cell.textContainView.frame = rect;
    cell.mingchengLabel.text = nyp.public_product_name;
    
    //设置状态label 的元素状态
    NYElement *nye = nil;
    for(NYElement *element in [MenuDataManager sharedManager].elements)
    {
        if([element.elementId isEqualToString:kOnlineProductStatusLabelId])
        {
            nye = element;
            break;
        }
    }
    cell.statusLabel.text = nyp.status;
    if(nye.elementAccess == kElementInvisiable)
    {
        cell.statusLabel.hidden = YES;
    }
    else
    {
        cell.statusLabel.hidden = NO;
    }
    cell.liangdianLabel.text = nyp.product_feature;
    cell.shouyilvLabel.text = nyp.product_yield;
    cell.nianxianLabel.text = nyp.product_term;

        cell.markImageView.hidden = YES;

    return cell;
}

#pragma mark - UITableViewDelegate methods

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NYProduct *nyp = [self.keepProductList objectAtIndex:indexPath.row];
    ProductDetailViewController *pdvc = [[ProductDetailViewController alloc] init];
    pdvc.isForCollect = YES;
    pdvc.product = nyp;
    [self.navigationController pushViewController:pdvc animated:YES];
    [pdvc release];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return kOnlineProductTableCellHeight;
}

#pragma mark - MoreViewDelegate method
- (void)didMoreViewClicked
{
    ++kCurrentPageNum;
    [self callServerToGetMyKeep];
}

@end
